/**
 * 扩展jQuery方法
 * @param $
 */
(function($){
	$.extend({
		/**
		 * 产生客户端全球唯一ID，总长32位。
		 * 示例如下：<br>
		 * var mid = $.uuid(); // 产生一个随机的uuid，mid="E1D415BD31B9D00017CC510F070521652"
		 * var midx = $.uuid("HH"); // 产生一个随机的uuid，该uuid以HH开头，midx="HHD415BD31B9D00017CC510F07052165"
		 * @param  {Object} prefix 可选项，UUID前缀
		 */
		uuid: function(prefix) {
			prefix = prefix || "E";
			var _getIntegerBits = function(val, start, end) {
			    var base16 = _returnBase(val, 16);
			    var quadArray = new Array();
			    var quadString = '';
			    var i = 0;
			    for (i = 0; i < base16.length; i++) {
			        quadArray.push(base16.substring(i, i + 1));
			    }
			    for (i = Math.floor(start / 4); i <= Math.floor(end / 4); i++) {
			        if (!quadArray[i] || quadArray[i] == '') quadString += '0';
			        else quadString += quadArray[i];
			    }
			    return quadString;
			};
			var _returnBase = function(number, base) {
			    var convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H',
			            'I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
			    var output = null;
			    if (number < base) {
			    	output = convert[number];
			    } else {
			        var MSD = '' + Math.floor(number / base);
			        var LSD = number - MSD * base;
			        if (MSD >= base) {
			        	output = _returnBase(MSD, base) + convert[LSD];
			        } else {
			        	output = convert[MSD] + convert[LSD];
			        } 
			    }
			    return output;
			};
			var _timeInMs = function(d) {
			    var ms_per_second = 100;
			    // constant
			    var ms_per_minute = 6000;
			    // ms_per second * 60;
			    var ms_per_hour = 360000;
			    // ms_per_minute * 60;
			    var ms_per_day = 8640000;
			    // ms_per_hour * 24;
			    var ms_per_month = 207360000;
			    // ms_per_day * 30;
			    var ms_per_year = 75686400000;
			    // ms_per_day * 365;
			    return Math.abs((d.getUTCFullYear() * ms_per_year) +
			                    (d.getUTCMonth() * ms_per_month) +
			                    (d.getUTCDate() * ms_per_day) +
			                    (d.getUTCHours() * ms_per_hour) +
			                    (d.getUTCMinutes() * ms_per_minute) +
			                    (d.getUTCSeconds() * ms_per_second) +
			                    d.getUTCMilliseconds());
			};
			var _randrange = function(min, max) {
			    var num = Math.round(Math.random() * max);
			    if (num < min) {
			        num = min;
			    } else if (num > max) {
			        num = max;
			    }
			    return num;
			};
			var dg = _timeInMs(new Date(1582, 10, 15, 0, 0, 0, 0));
		    var dc = _timeInMs(new Date());
		    var t = dc - dg;
		    var h = '';//分隔符
		    var tl = _getIntegerBits(t, 0, 31);
		    var tm = _getIntegerBits(t, 32, 47);
		    var thv = _getIntegerBits(t, 48, 59) + '1';
		    var csar = _getIntegerBits(_randrange(0, 4095), 0, 7);
		    var csl = _getIntegerBits(_randrange(0, 4095), 0, 7);
		    var n = _getIntegerBits(_randrange(0, 8191), 0, 7) +
		            _getIntegerBits(_randrange(0, 8191), 8, 15) +
		            _getIntegerBits(_randrange(0, 8191), 0, 7) +
		            _getIntegerBits(_randrange(0, 8191), 8, 15) +
		            _getIntegerBits(_randrange(0, 8191), 0, 15);
		    // this last number is two octets long
		    var oRs = prefix + tl + h + tm + h + thv + h + csar + csl + h + n;
		    var rs = oRs.substring(0, 31);
		    return rs;
		},
		/**
		 * jquery plugins
		 * @功能：将数组形式的对象转为树形结构的对象
		 * @作者：lj
		 * @日期：2017-04-03
		 */
		// 对于tree而言，options中必须定义的项：
		//{
//			"data":[]
//			"rootPidValue":null,
//			"children":"children",
//			"contentDefine":{
//				"id":"id",
//				"pid":"pid"
//			}
		//}
		toTree:function(options){
			if(!options){
				options = {};
			}
			var data = options.data;
			var contentDefine = options.contentDefine;
			
			var getChild = function(mData,pid){
				var menus = [];
				$.each(mData,function(index,item){
					if(item[contentDefine.pid] == pid){
						var obj = new Object();
						$.extend(obj,item);
						
						$.each(contentDefine,function(key,val){
							obj[key] = item[val];
						});
						
						var children = getChild(mData,item[contentDefine.id]);
						obj[options.children] = children;
						menus.push(obj);
					}
				});
				return menus;
			};
			return getChild(data,options.rootPidValue);
		},
		/**
		 * jquery plugins
		 * @功能：将树形结构转为列表结构
		 * @参数：{data[],levelKey,pidKey,idKey,rootPidValue,childrenKey}
		 * @作者：lj
		 * @日期：2017-08-22 
		 */
		treeToList:function(options) {
			var opt = {
				'levelKey':'level',
				'pidKey':'pid',
				'idKey':'id',
				'rootPidValue':null,
				'childrenKey':'children',
			};
			$.extend(opt, options);
			if (opt.data == null ) {
				return null;
			}
			if (!ArrayUtil.isArray(opt.data)) {
				var x = new Array(1);
				x[0] = opt.data;
				opt.data = x;
			}
			var result = new Array();
			var toList = function(arr, rs, mlevel, pid) {
				if (arr == null) {
					return ;
				}
				for (var i = 0; i < arr.length; i ++ ) {
					var children = arr[i][opt.childrenKey];
					opt.levelKey && (arr[i][opt.levelKey] = mlevel);
					arr[i][opt.pidKey] = pid;
					if (children != null) {
						delete arr[i][opt.childrenKey];
					}
					rs.push(arr[i]);
					toList(children, rs, mlevel + 1, arr[i][opt.idKey]);
				}
			};
			toList(opt.data, result, 1, opt.rootPidValue);
			return result;
		},
		/**
		 * jquery plugins
		 * @功能：将对象数组转为单一的某个属性值组成的数组
		 * @示例：输入 
		 * <p>var arr = [{'id':1,'name':'tom'},{'id':2,'name':'susan'}];</p>
		 * <p>var property = 'id';</p>
		 * <p>var result = $.toPropertyArray(arr,property)</p>
		 * <p>// result=[1,2]</p>
		 * @作者：lj
		 * @日期：2017-04-21 
		 */
		toPropertyValueArray:function(array,property){
			var arr = [];
			if(!array || array.length<=0 || !array instanceof Array){
				return arr;
			}
			$.each(array,function(index,item){
				arr.push(item[property]);
			});
			return arr;
		},
		/**
		 * @功能：根据属性名和属性值获取对象数组中的对象
		 * @示例：
		 * <code>var arr = [{'id':0,'name':'tom','age':11},{'id':1,'name':'army','age':17},{'id':2,'name':'tomseny','age':21}];
		 * var rs = $.getObjectOfArrayByPropertyValue(arr,'name','tomseny'); // rs = {'id':2,'name':'tomseny','age':21}</code>
		 * @作者：lj
		 * @日期：2017-05-21 
		 */
		getObjectOfArrayByPropertyValue:function(array, property, value) {
			if (!array || array.length == 0) {
				return null;
			}
			if (!property || StringUtil.isBlank(property)) {
				throw new Error('parameter:property is not defined');
			}
			for (var i = 0; i < array.length; i++ ) {
				var obj = array[i];
				if (obj && obj[property] && obj[property] == value) {
					return obj;
				}
			}
			return null;
		},
		/**
		 * @功能：将对象数组中的某一列作为对象的key，将对象数组的另一列作为value，返回key,value组成的对象
		 * @示例：
		 * <code>var arr = [{'id':0,'name':'tom','age':11},{'id':1,'name':'army','age':17},{'id':2,'name':'tomseny','age':21}];
		 * var rs = $.arrayToObject(arr,'name','age'); // rs = {'tom':11,'army':17,'tomseny':21}</code>
		 * @作者：lj
		 * @日期：2017-08-12 
		 */
		arrayToObject:function(arr, kkey, vkey) {
			if (!ArrayUtil.hasData(arr)) {
				return {};
			}
			var obj = {};
			$.each(arr, function(index, item) {
				var key = item[kkey];
				var value = item[vkey];
				obj[key] = value;
			});
			return obj;
		},
		/**
		 * @功能：session超时统一处理
		 * @作者：刘杰
		 * @日期：20170526
		 */
		sessionTimeoutHandle:function(xhr, textStatus) {
			var handle = function() {
				if (!xhr.hasDone) {
					MsgBox.stopLoading();
					// 如果超时就处理 ，指定要跳转的页面
					MsgBox.error("会话超时，立即重新登录", null, function() {
						top.window.location.href = ctx;
					});
					xhr.hasDone = true;
				}
			};
			
			if (xhr.getAllResponseHeaders().contains("sessionstatus:timeout")) {
				handle();
				return ;
			}
			
			//通过XMLHttpRequest取得响应头，sessionstatus，  
	        var sessionstatus=xhr.getResponseHeader("sessionstatus");   
	        Logger.warn("sessionStatus = " + sessionstatus);
	        if(sessionstatus=="timeout"){
	        	handle();
	        	return ;
	        }
		},
		/**
		 * @功能：自定义ajax请求，系统中所有的ajax请求均应该用此ajax请求
		 * @作者：刘杰
		 * @日期：20170526
		 */
		mAjax:function(options) {
			var opt = {
				'timeout': 30000, // 默认超时时间设置为30秒
			};
			$.extend(opt, options);
			opt.mcomplete = opt.complete;
			opt.msuccess = opt.success;
			delete opt.complete;
			delete opt.success;
			var setting = {
				'complete':function(xhr, status) {
					MsgBox.stopLoading();
					$.sessionTimeoutHandle(xhr, status);
					ObjectUtil.isFunction(opt.mcomplete) && opt.mcomplete(xhr, status);
				},
				'success':function(data, status, xhr) {
					MsgBox.stopLoading();
					$.sessionTimeoutHandle(xhr, status);
					ObjectUtil.isFunction(opt.msuccess) && opt.msuccess(data, xhr, status);
				}
			};
			$.extend(setting, opt);
			if (!opt.silent) {
				MsgBox.startLoading();
			}
			$.ajax(setting);
		},
		/**
		 * 简单的存储工具
		 */
		store:{
			map:{},
			set:function(key,val) {
				$.store.map[key]=val;
			},
			get:function(key) {
				return $.store.map[key];
			},
			deleteKey:function(key) {
				if ($.get(key)) {
					$.set(key, null);
				}
			}
		},
		getTopBody:function() {
			if (top == null || top.document == null || top.document.body == null)  {
				throw new Error();
			}
			return $(top.document.body);
		},
		/**
		 * jquery plugins
		 * $('#xx').mBuildSelect({})
		 * @属性：<p>id,name,className,
		 * showSelectAll,showSelectName,showSelectValue,readonly,defaultValue,
		 * data[{value,text}],defaultIndex,contentDefine{text,value},onValueChanged</p>
		 * @功能：下拉菜单
		 * @作者：lj
		 * @日期：2017-05-31
		 * @调用：dropList.tag
		 */
		_buildSelect:function(options) {
			var opt = {
				'showSelectName':'全部',
				'showSelectValue':'',
				'contentDefine':{
					'text':'text',
					'value':'value'
				}
			};
			opt = $.extend(opt, options);
			var $select = $("<select/>");
			$select.attr({
				'id':opt.id,
				'name':opt.name
			});
			if (opt.readonly) {
				$select.attr({
					'disabled':'disabled',
					'readonly':'readonly'
				});
			}
			opt.className && $select.attr('class',opt.className);
			if (opt.showSelectAll) {
				var $option = $('<option/>');
				$option.attr({
					'value':opt.showSelectValue
				});
				if (!opt.defaultValue) {
					$option.attr('selected', 'selected');
				}
				$option.text(opt.showSelectName);
				$select.append($option);
			}
			if ( ArrayUtil.hasData(opt.data)) {
				$.each(opt.data, function(index, item) {
					var $option = $('<option/>');
					$option.attr({
						'value':item[opt.contentDefine.value],
						'data-index':index
					});
					$option.text(item[opt.contentDefine.text]);
					$select.append($option);
				});
			}
			if (ObjectUtil.isInteger(opt.defaultIndex)) {
				var defaultIndex = parseInt(opt.defaultIndex);
				if (defaultIndex < 0) defaultIndex = 0;
				if (ArrayUtil.hasData(opt.data) && defaultIndex >= opt.data.length) defaultIndex = opt.data.length-1;
				$select.find('option[data-index="' + defaultIndex + '"]').attr('selected','selected');
			}
			if (opt.defaultValue) {
				$select.find('option[value="' + opt.defaultValue + '"]').attr('selected','selected');
			}
			if (opt.onValueChanged && ObjectUtil.isFunction(opt.onValueChanged)) {
				$select.on('input propertychange', function() {
					opt.onValueChanged();
				});
			}
			return $select;
		},
		/**
		 * @功能 构造一个带小图标的超链接
		 * @参数 options{type,className,click->function,title}
		 * @日期 20170615
		 */
		buildIconLink:function(options) {
			var opt = {
				'ICON_TYPE':{
					'edit':{   'className': 'icon icon-edit'  },
					'delete':{ 'className': 'icon icon-trash' },
					'view':{   'className': 'icon icon-eye-open' },
					'reply':{  'className': 'icon icon-reply'   },
					'point':{  'className':'icon icon-hand-right' },
					'forbid':{ 'className':'icon icon-minus-sign m-color-red'}
				}
			};
			$.extend(opt, options);
			var $link = $("<a href='javascript:void(0);'></a>");
			var $icon = $("<i></i>");
			opt.type && $icon.addClass(opt.ICON_TYPE[opt.type].className);
			opt.className && $icon.addClass(opt.className);
			opt.click && $link.off('click').on('click',function(e) {
				e.stopPropagation();
				e.preventDefault();
				opt.click(e);
			});
			$link.append($icon);
			$link.attr({
				'title':(opt.title || ''),
				'class':'m-icon-link'
			});
			return $link;
		},
		/**
		 * @功能 构建自定义对话框
		 * @参数 {name,title,url,width,height,mode,closeFunc,okOpt{okName,okFunc},cancelOpt{cancelName,cancelFunc}}
		 * @日期 20170709
		 */
		buildDialog:function(options) {
			var opt = {
				'mode':'iframe'
			};
			$.extend(opt,options);
			var windowKey = $.getWindowKey();
			var $odialog = $(".dialog-box[data-dialog-id='" + windowKey + "'][data-name='" + opt.name + "']");
			var len = $odialog.length;
			if(len > 0) {
				return ;
			}
			
			// close dialog
			var closeDialog = function($dialog, func, e) {
				func && func(e);
				$dialog.fadeOut(1000,function(){
					$dialog.remove();
				});
			};
			// dialog 对象
			var dialog = function($dialog){
				return {
					'close':function() {
						$dialog.hide(1000, function(){
							$dialog.remove();
						});
					}
				};
			};
			// 适应位置
			var fixPosition = function($popBox) {
				var wh = $(top.window).height(); // window height
				var ph = $popBox.height();
				var mTop = (wh - ph) * 0.3;
				
				var ww = $(top.window).width();
				var pw = $popBox.width();
				var mLeft = (ww - pw) * 0.5;
				
				$popBox.css('top', mTop + 'px');
				$popBox.css('left', mLeft + 'px');
			};
			// output dialog header
			var outputDialogHeader = function($dialogHeader, opt, $dialog) {
				var $closeBtn = $("<button class='box-close-btn' data-dismiss='dialog-box' data-close='true'>×</button>");
				var $title = $("<h4 class='box-title'></h4>");
				$title.text(opt.title);
				$closeBtn.off('click').on('click', function(e){
					e.preventDefault();
					e.stopPropagation();
					closeDialog($dialog, opt.closeFunc, e);
				});
				$dialogHeader.append($closeBtn);
				$dialogHeader.append($title);
			};
			// output dialog footer
			var outputDialogFooter = function($dialogFooter, opt, $dialog) {
				var okOpt = opt.okOpt;
				if (okOpt) {
					var $ensureBtn = $("<button class='btn btn-primary m-btn' data-id='ensure'></button>");
					$dialogFooter.append($ensureBtn);
					okOpt.okName ? $dialogFooter.text(okOpt.okName) : $dialogFooter.text('确定');
					$ensureBtn.off('click').on('click', function(e){
						okOpt.okFunc && okOpt.okFunc(dialog($dialog), e);
					});
				}
				var cancelOpt = opt.cancelOpt;
				if (cancelOpt) {
					var $cancelBtn = $("<button class='btn btn-default m-btn' data-id='cancel' data-dismiss='dialog-box'></button>");
					if (cancelOpt && cancelOpt.cancelName) {
						$cancelBtn.text(cancelName);
					} else {
						$cancelBtn.text('关闭');
					}
					$cancelBtn.off('click').on('click', function(e) {
						var cancelFunc = opt.cancelOpt ? opt.cancelOpt.cancelFunc : null;
						closeDialog($dialog, cancelFunc, e);
					});
					$dialogFooter.append($cancelBtn);
				}
				if (!(okOpt && okOpt)) {
					$dialogFooter.remove();
				}
			};
			// output dialog body
			var outputDialogBody = function($dialogBody, opt, $dialog) {
				var $popBox = $dialog.find(".pop-box");
				var popBoxHeight = $popBox.height();
				if (opt.mode == 'iframe') {
					var height = null;
					if (popBoxHeight > 0) {
						height = (popBoxHeight - 42) + 'px';
						if (opt.okOpt || opt.cancelOpt) {
							height = (popBoxHeight - 90) + 'px';
						}
					}
					$dialogBody.loadPageByIframe({
						'url':opt.url,
						'height': height,
						'iframeAttr':{
							'data-dialog-iframe':true,
							'data-pid':$.getWindowKey()
						},
						'onReadyStateChanged':function($iframe){
							var mWindow = $iframe[0].contentWindow;
							var mDocument = mWindow.document;
							var $body = $(mDocument.body);
							$body.find("[data-dismiss='dialog-box']").off('click').on('click', function(e){
								e.stopPropagation();
								e.preventDefault();
								closeDialog($dialog);
							});
							var resetHeight = function() {
								var height = $body.height() + 52;
								$iframe.attr("height", height);
							};
							// 重新定义高度
							if (popBoxHeight == 0) {
								resetHeight();
								fixPosition($popBox);
							}
							// 在加载完页面的1秒钟内不停的调整页面高度，适应页面位置
							for (var i = 0 ; i < 10; i++) {
								setTimeout(function() {
									resetHeight();
									fixPosition($popBox);
								}, 250);
							}
						}
					});
					$dialogBody.css('display','inline');
				} else {
					$dialogBody.css('height',(popBoxHeight - 90));
					$dialogBody.loadPage({
						'url':opt.url,
						'type':'get'
					});
				}
			};
			
			var $dialog = $("<div class='dialog-box' data-dialog='true' style='display:none'></div>");
			
			$.getTopBody().find(".dialog-box[data-dialog-current='true']").attr("data-dialog-current",false); // 当前对话框切换
			$dialog.attr({
				'data-dialog-id':windowKey,
				'data-name':opt.name,
				'data-dialog-current':true
			});
			// 获取打开的对话框最大的z-index
			var getDialogMaxZIndex = function() {
				var maxZIndex = 0;
				$.getTopBody().find(".box-layer").each(function(e){
					var zindex = $(this).css("z-index");
					if (zindex > maxZIndex) {
						maxZIndex = zindex;
					}
				});
				return maxZIndex;
			};
			
			var maxZIndex = getDialogMaxZIndex();
			var $boxLayer = $("<div class='box-layer'></div>");
			$boxLayer.css("z-index", maxZIndex + 100);
			
			var $popBox = $("<div class='pop-box'>" +
								"<div class='box-header'></div>" +
								"<div class='box-body'></div>" +
								"<div class='box-footer'></div>" +
							"</div>");
			$popBox.css("z-index", maxZIndex + 101);
			opt.width && $popBox.css('width', opt.width);
			opt.height && $popBox.css('height', opt.height);
			
			outputDialogHeader($popBox.find(".box-header"), opt, $dialog);
			outputDialogFooter($popBox.find(".box-footer"), opt, $dialog);
			$dialog.append($boxLayer);
			$dialog.append($popBox);
			$.getTopBody().append($dialog);
			outputDialogBody($popBox.find(".box-body"), opt, $dialog);
			$dialog.fadeIn({
				'speed':1000
			});
			// 设置拖动
			$popBox.easydrag($popBox.find(".box-header"));
			
			fixPosition($popBox);
			$(top.window).resize(function(){
			    fixPosition($popBox);
			});
		},
		/**
		 * @功能 构建提示信息对话框
		 * @参数 {type,message, title, okfunc}
		 * @日期 20170709
		 */
		buildPromptDialog:function(type,message, title, okfunc) {
			var MSGBOX_STYLES = $.store.get("MsgBoxStyle");
			if (!MSGBOX_STYLES) {
				MSGBOX_STYLES = {
					success:{ icon:'fa fa-fw fa-check-circle', style:'alert-success',  defaultTitle:'成功'},
					error:{   icon:'fa fa-fw fa-times-circle', style:'alert-danger',   defaultTitle:'错误'},
					info:{    icon:'fa fa-fw fa-info-circle',  style:'alert-info',     defaultTitle:'信息'},
					warn:{    icon:'fa fa-fw fa-warning',      style:'alert-warning',  defaultTitle:'警告'},
					confirm:{ icon:'fa fa-fw fa-inbox',        style:'alert-confirm',  defaultTitle:'确认'}
				};
				$.store.set("MsgBoxStyle", MSGBOX_STYLES);
			}
			var style = MSGBOX_STYLES[type]; // 根据对话框类型选择样式
	    	
			$.getTopBody().find("#" + type).remove();
    		// 拼接对话框的html代码
    		var $dialog = $("<div class='modal fade'/>");
    		$dialog.attr({
    			'tabindex':'-1',
    			'data-dialog':'true',
    			'role':'dialog',
    			'aria-hidden':'true',
    			'data-backdrop':'static',
    			'id':type
    		});
    		var $modalDialog = $("<div class='modal-dialog '/>");
    		var $modalContent = $("<div class='modal-content '/>");
    		var $modalHeader = $("<div class='modal-header '/>");
    		var $modalTitle = $("<h4 class='modal-title '/>");
    		var $closeBtn = $("<button/>");
    		$closeBtn.attr({
    			'type':'button',
    			'class':'close',
    			'data-dismiss':'modal',
    			'data-close':true
    		});
    		$closeBtn.append("<span aria-hidden='true'>&times;</span>");
    		$closeBtn.append("<span class='sr-only'>Close</span>");
    		$modalHeader.append($closeBtn);
    		$modalHeader.append($modalTitle);
    		var $modalBody = $("<div class='modal-body '/>");
    		var $alert = $("<div class='alert with-icon'/>");
    		$alert.append("<i/>");
    		var $content = $("<div class='content'/>");
    		var $mcontent = $("<strong/>");
    		$content.append($mcontent);
    		$alert.append($content);
    		$modalBody.append($alert);
    		var $modalFooter = $("<div class='modal-footer '/>");
    		var $ensureBtn = $("<button class='btn btn-primary'/>");
    		$ensureBtn.attr({
    			'type':'button',
    			'data-dismiss':'modal',
    			'data-id':'ensure'
    		});
    		$ensureBtn.text("确定");
    		$modalFooter.append($ensureBtn);
    		$modalContent.append($modalHeader);
    		$modalContent.append($modalBody);
    		$modalContent.append($modalFooter);
    		$modalDialog.append($modalContent);
    		$dialog.append($modalDialog);
    		$.getTopBody().append($dialog);
    		
	    	$dialog.find('.modal-title').text(title || style.defaultTitle);
	    	$dialog.find(".alert").prop("class","alert "+style.style+" with-icon");
	    	$dialog.find(".alert>i").prop("class",style.icon);
	    	$dialog.find(".content>strong").text(message ? message : '');
	    	// 绑定事件
	    	$dialog.find("button[data-id='ensure']").off('click')
	    			.on('click', function(e){
	    				setTimeout(function(){
	    					okfunc && okfunc();
	    				}, 500);
	    			});
	    	if(type=='confirm') {
	    		var $button = $dialog.find(".modal-footer>button[data-id='cancel']");
	    		if($button.length==0){
	    			$button = $("<button/>").attr({
	    				"type":"button",
	    				"class":"btn btn-default",
	    				"data-dismiss":"modal",
	    				"data-id":"cancel"
	    			});
	    			$button.text("取消");
	    			$dialog.find(".modal-footer").append($button);
	    		}
	    		$button.off('click').on('click', function(e){
	    			setTimeout(function(){
	    				cancelFunc && cancelFunc();
	    			}, 500);
				});
	    	}
    		$dialog.modal();
		},
		'getWindowKey':function() {
			var windowKey = null;
			$.getTopBody().find("iframe").each(function() {
				if (this.contentWindow == window) {
					windowKey = $(this).data('id');
				}
			});
			if (windowKey == null) {
				windowKey = 'top';
			}
			return windowKey;
		},
		'getMousePosition': function(e) {
			var posx = 0;
			var posy = 0;
	
			if (!e) e = top.window.event;
	
			if (e.pageX || e.pageY) {
				posx = e.pageX;
				posy = e.pageY;
			} else if (e.clientX || e.clientY) {
				posx = e.clientX + top.document.body.scrollLeft + top.window.document.documentElement.scrollLeft;
				posy = e.clientY + top.document.body.scrollTop + top.window.document.documentElement.scrollTop;
			}
	
			return {
				'x': posx,
				'y': posy
			};
		},
		/**
		 * jquery plugins
		 * @功能：漂浮消息提示
		 * @作者：lj
		 * @日期：2017-04-20
		 */
		messager:{
			warn:function(msg,options){$.messager._show(msg,'warning',options);},
			info:function(msg,options){$.messager._show(msg,'info',options);},
			error:function(msg,options){$.messager._show(msg,'danger',options);},
			success:function(msg,options){$.messager._show(msg,'success',options);},
			important:function(msg,options){$.messager._show(msg,'important',options);},
			_show:function(msg,type,options){
				if (window != top) {
					top.$.messager._show(msg, type, options);
					return ;
				}
				var mOptions = {
					'type': type,
					'time': 2000,
				};
				$.extend(mOptions,options);
				// 删除消息
				var removeMessager = function($messager){
					$messager.slideUp(150, 'swing', function(){
						$messager.remove();
					});
				};
				var showMessager = function($messager) {
					$messager.fadeIn(200);
				};
				// 构造消息
				var buildMessager = function(msg, type, opt) {
					var MESSAEGR_SETTINGS = $.store.get("MESSAEGR_SETTINGS");
					if (!MESSAEGR_SETTINGS) {
						MESSAEGR_SETTINGS = {
							'warning':{   'className':'messager-warning' },
							'info':{      'className':'messager-info' },
							'danger':{    'className':'messager-danger' },
							'success':{   'className':'messager-success' },
							'important':{ 'className':'messager-important' }
						};
						$.store.set(MESSAEGR_SETTINGS);
					}
					var $messagerHolder = $.getTopBody().find(".messager-holder");
					if ($messagerHolder.length < 1 ){
						$messagerHolder = $("<div class='messager-holder'></div>");
						$.getTopBody().append($messagerHolder);
					}
					
					var $messager = $("<div class='messager' style='display:none;'></div>");
					$messager.addClass(MESSAEGR_SETTINGS[type]['className']);
					var $messageContent = $("<div class='messager-content'></div>");
					$messageContent.text(msg);
					$messager.append($messageContent);
					
					var size = $messagerHolder.find(".messager").length;
					var topVal = (size*50) + "px";
					$messager.css("top", topVal);
					
					var $messagerActions = $("<div class='messager-actions'></div>");
					var $closeBtn = $("<button type='button' class='action action-close'>×</button>");
					$closeBtn.off('click').on('click', function(e) {
						removeMessager($messager);
					});
					$messagerActions.append($closeBtn);
					$messager.append($messagerActions);
					
					$messagerHolder.append($messager);
					return $messager;
				};
				var $messager = buildMessager(msg, type, mOptions);
				showMessager($messager);
				
				setTimeout(function(){
					removeMessager($messager);
				}, mOptions.time);
			}
		},
		/**
		 * jquery plugins
		 * @功能：下载文件
		 * @作者：lj
		 * @参数：{url,type,data}
		 * @日期：2017-8-15
		 */
		download:function(options) {
			var opt = {
				'type':'get'
			};
			$.extend(opt, options);
			var $frm = $("<form></form");
			$frm.attr({
				'action': opt.url,
				'method': opt.type
			});
			if (opt.data != null) {
				$.each(opt.data, function(key, value) {
					var $input = $("<input hidden='hidden'>");
					$input.attr({
						'name': key,
						'value': value
					});
					$frm.append($input);
				});
			}
			$frm.appendTo("body").submit().remove();
		},
		/**
		 * jquery plugins
		 * @功能：指定策略生成ID
		 * @作者：lj
		 * @参数：strategy
		 * @日期：2017-08-19 
		 */
		'generateId':function(strategy) {
			var idStrategy = $.store.get("ID_STRATEGY");
			if (!idStrategy) {
				idStrategy = {
					'uuid':function() {
						return $.uuid();
					},
					'timestamp':function() {
						return (new Date()).getTime();
					}
				};
				$.store.set("ID_STRATEGY", idStrategy);
			}
			return idStrategy[strategy] ? idStrategy[strategy]() : '';
		},
		/**
		 * @功能：获取时间戳
		 * @作者：lj
		 * @日期：2017-08-22
		 */ 
		'timestamp':function() {
			return (new Date()).getTime();
		},
		/**
		 * @功能：在单击事件中，排除双击事件
		 * @作者：lj
		 * @参数：key:区别于其它的点击事件，duration：区分单击双击的时间间隔，onClick：单击时触发的事件
		 * @日期：2017-08-22 
		 */
		excludeDbClick:function(key, duration, onClick) {
			var startTime = $.timestamp();
            var KEY = "LAST_CLICK_TIME_" + key;
            var TIME_OUT_KEY = "TIMEOUT_" + key;
            var lastTime = $.store.get(KEY) || 0;
            var st = $.store.get(TIME_OUT_KEY);
            if (startTime -  lastTime > duration) {
            	st = setTimeout(function() {
            		onClick && onClick();
            		clearTimeout(st);
            		$.store.set(TIME_OUT_KEY, null);
            	}, duration);
            	$.store.set(TIME_OUT_KEY, st);
            } else {
            	if (st != null ) {
            		clearTimeout(st);
            		$.store.set(TIME_OUT_KEY, null);
            	}
            }
            $.store.set(KEY, startTime);
		},
		/**
		 * @功能：获取树及其节点的深度，适用于树形结构
		 * @作者：lj
		 * @参数：{node,childrenKey,idKey}
		 * @日期：2017-08-22 
		 */
		getTreeDepth:function(node, childrenKey, idKey) {
			if (node == null) {
				return 0;
			}
			var newNode = $.extend({}, node);
			var arr = $.treeToList({
				'data':newNode,
				'rootPidValue':null,
				'idKey':idKey,
				'pidKey':'pid',
				'childrenKey':childrenKey,
				'levelKey':'level'
			});
			var levelArray = $.toPropertyValueArray(arr, 'level');
			return ArrayUtil.max(levelArray);
		},
		/**
		 * @功能：将Object对象转为form表单可识别的xx.yy形式的对象
		 * @作者：lj
		 * @参数：obj
		 * @日期：2017-08-27 
		 */
		formObj:function(obj) {
			if (!ObjectUtil.isSimpleObject(obj)) {
				return obj;
			}
			var dealObj = function(obj, mkey, mobj) {
				if (!ObjectUtil.isSimpleObject(mobj)) {
					return true;
				}
				$.each(mobj, function(nkey, nval) {
					var okey = mkey + "." + nkey;
					obj[okey] = nval;
					if (!dealObj(obj, okey, nval)) {
						delete obj[okey];
					}
				});
			};
			$.each(obj, function(key, val) {
				if (!dealObj(obj, key, val)) {
					delete obj[key];
				}
			});
			return obj;
		}
	});
})(jQuery);


